<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Date时间</title>
</head>
<style>

</style>
<body>
  <p>5秒跳转百度</p>
  <button>取消</button>
  <p></p>
  
</body>
<script>
  // var time1 = new Date().getTime();

  // setInterval(() => {
  //   var time2 = new Date().getTime();
  //   console.log(time2 - time1);
  //   time1 = time2;
  // }, 1000);

  var p = document.getElementsByTagName("p")[0],
      btn = document.getElementsByTagName("button")[0];

  p.onclick = function(){
    var i = setTimeout(() => {
      location.href = "http://baidu.com";
    }, 5000);
  }
  btn.onclick = function(){
    clearTimeout(i);
    p.innerHTML = "已取消";
  }

  /**
   * 作业
   * 1、在原型上编程，写一个数组时钟
   * 2、在原型上编程，写一个倒计时
  */
  Object.prototype.Arrshizhong = function(){
    var p = document.createElement("p");
    var tep = function(num){
      num += "";
      return num.length < 2 ? "0" + num : num;
    }
    setInterval(() => {
      var year = new Date().getFullYear(),
        yue = new Date().getMonth() + 1,
        ri  = new Date().getDate(),
        shi = new Date().getHours(),
        fen = new Date().getMinutes(),
        miao = new Date().getSeconds();
        // console.log(year, yue, ri, shi, fen, miao);
        var str = year + "-" + tep(yue) + "-" + tep(ri) + " " 
                  + tep(shi) + ":" + tep(fen) + ":" + tep(miao);
        // console.log(str);
        p.innerHTML = str;
    }, 1000);
    document.body.appendChild(p);
  }
  Date().Arrshizhong();
  

  /***********************************************************/
  //倒计时
  Date.prototype.countDown = function(endTime, timer){
    var newTime = this.getTime(),
        leftTime = (endTime - newTime) / 1000,
        d, h, m, s, str;
    var db = document.createElement("p");    

    var te = function(num){
      num += "";
      return num.length < 2 ? "0" + num : num
    }
    if(leftTime >= 0){
      d = Math.floor(leftTime / 60 / 60 / 24); //day
      h = Math.floor(leftTime / 60 / 60 % 24);
      m = Math.floor(leftTime / 60 % 60);
      s = Math.floor(leftTime % 60);
    }else{
      clearInterval(timer);
    }
    str = `${te(d)}天${te(h)}时${te(m)}分${te(s)}秒`;
    return str;
  }

  var op = document.getElementsByTagName("p")[1];
  var endTime = new Date(2021, 5, 23, 21, 59, 50).getTime(),
      t = null;
  t = setInterval(() => {
    op.innerHTML = new Date().countDown(endTime, t);
  }, 1000);
  







</script>
</html>